/**
 * Created by kang on 2016/8/22.
 */
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var Log = require('../utils/logger');
var dbManager = require('../utils/db-manager');
var ObjectID = require('mongodb').ObjectID;

router.use(bodyParser.json()); // for parsing application/json
router.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded

router.restPath = "/report";

router.get('/', function (req, res, next) {
    var logger = Log.getLogger("get reports");
    //TODO:check the request body
    var collection = dbManager.db.collection('Report');
    collection.find({}).toArray(function(error, result){
        if(error || !result){
            logger.error(error.name + ": " + error.message);
            res.status(404).json({
                name: error.name,
                message: error.message
            });
        }else{
            res.json(result);
        }
    })
});


/* new report */
router.post('/', function (req, res, next) {
    var logger = Log.getLogger("new report");

    //TODO:check the request body, file type check
    var reqBody = req.body;

    if(reqBody.testPlanID==undefined) {
        logger.error("report: testPlanID is required");
        res.status(404).json({
            message: "report: testPlanID is required"
        }).end();
        return;
    }

    var report = {
        testPlanID:reqBody.testPlanID,
        content:reqBody.content
    };

    try {
        var testPlanCollection = dbManager.db.collection('TestPlan');
        testPlanCollection.find({_id: new ObjectID(report.testPlanID)}).next(function (err, result) {
            if (err || !result) {
                var error = {};
                error.name = err ? err.name : "New Report error";
                error.message = err ? err.message : "TestPlan of " + report.testPlanID + " couldn't be found.";
                logger.error(error.name + ": " + error.message);
                res.status(404).json({
                    name: error.name,
                    message: error.message
                }).end();
                return;
            } else {
                // insert report
                var collection = dbManager.db.collection('Report');
                collection.insertOne(report).then(function (result) {
                    //location header of the response
                    logger.info("Report created: " + report._id);
                    res.status(200).json({
                        name: "success",
                        reportID: report._id
                    });
                }, function (error) {
                    logger.error("Save to collection:Report failed");
                    res.status(405).end();
                    return;
                });

                // push to test plan
                testPlanCollection.updateOne({_id: new ObjectID(report.testPlanID)},
                    {
                        $push: {'reportsID': report._id},
                        $set: {'lastRunStatus': 'Report created'}
                    })
                    .then(function (result) {
                        logger.info("TestPlan updated: " + report.testPlanID);
                    }, function (error) {
                        logger.error("TestPlan update failed");
                        res.status(405);
                    });
            }
        });
    }catch(error){
    logger.error(error.name + ": " + error.message);
    res.status(404).json({
        name: error.name,
        message: error.message
    });
}
});

/* get report */
router.get('/:id', function (req, res, next){
    var tId = req.params.id;
    var logger = Log.getLogger("get report with id" );
    logger.info(tId);

    //TODO:check the request body

    var obID;
    try {
        obID = new ObjectID(tId);
    } catch (error) {
        var msg = {
            name:"new ObjectID error",
            message:error.toString()
        };
        logger.error(msg);
        res.status(404).json(msg).end();
        return;
    }
    var collection = dbManager.db.collection('Report');
    collection.find({_id: obID}).next(function(error, result){
        if(error){
            logger.error(error.name + ": " + error.message);
            res.status(404).json({
                name: error.name,
                message: error.message
            });
        }else{
            res.json(result);
        }
    })
});

module.exports = router;